<template>
  <div class="admin-dashboard">
    <!-- 动态背景 -->
    <div class="background-particles">
      <div class="particle" v-for="i in 5" :key="i" :style="getParticleStyle(i)"></div>
    </div>
    
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-left">
        <div class="logo">
          <el-icon size="32" color="#4ECDC4">
            <Monitor />
          </el-icon>
          <span class="logo-text">Cyan-Note</span>
        </div>
      </div>
      
      <div class="navbar-center">
        <h1 class="page-title">超级管理员控制台</h1>
      </div>
      
      <div class="navbar-right">
        <div class="user-info">
          <el-avatar 
            :size="36" 
            :src="userDisplayInfo.avatar" 
            :icon="UserFilled"
            class="user-avatar"
          />
          <div class="user-details">
            <div class="user-name">{{ userDisplayInfo.name }}</div>
            <div class="user-role">{{ userDisplayInfo.type }}</div>
          </div>
        </div>
        <el-button 
          type="danger" 
          size="small" 
          @click="handleLogout"
          class="logout-btn"
        >
          退出登录
        </el-button>
      </div>
    </div>

    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <div class="welcome-text">
          <h2>欢迎回来，{{ userDisplayInfo.name }}！</h2>
          <p>您有 {{ quickStats.totalShops }} 家店铺正在运营，系统运行状态良好</p>
        </div>
        <div class="banner-actions">
          <el-button type="primary" size="large" @click="navigateTo('/admin/shops')">
            <el-icon><Shop /></el-icon>
            管理店铺
          </el-button>
          <el-button type="success" size="large" @click="runHealthCheck">
            <el-icon><Connection /></el-icon>
            系统检查
          </el-button>
        </div>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card" @click="navigateTo('/admin/shops')">
          <div class="stat-icon shop">
            <el-icon size="32"><Shop /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ quickStats.totalShops }}</div>
            <div class="stat-label">店铺总数</div>
            <div class="stat-trend">
              <span class="trend-up">+{{ quickStats.activeShops }}</span>
              运营中
            </div>
          </div>
          <div class="stat-progress">
            <div class="progress-bar" :style="{width: (quickStats.activeShops/quickStats.totalShops*100) + '%'}"></div>
          </div>
        </div>

        <div class="stat-card" @click="navigateTo('/admin/managers')">
          <div class="stat-icon manager">
            <el-icon size="32"><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ quickStats.totalManagers }}</div>
            <div class="stat-label">店长账户</div>
            <div class="stat-trend">
              <span class="trend-up">+{{ quickStats.activeManagers }}</span>
              正常
            </div>
          </div>
          <div class="stat-progress">
            <div class="progress-bar manager" :style="{width: (quickStats.activeManagers/quickStats.totalManagers*100) + '%'}"></div>
          </div>
        </div>

        <div class="stat-card" @click="navigateTo('/admin/monitoring')">
          <div class="stat-icon system">
            <el-icon size="32"><Monitor /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ systemUptime }}</div>
            <div class="stat-label">系统运行</div>
            <div class="stat-trend">
              <span class="trend-stable">{{ systemStatus }}</span>
            </div>
          </div>
          <div class="stat-progress">
            <div class="progress-bar system" style="width: 85%"></div>
          </div>
        </div>

        <div class="stat-card" @click="runHealthCheck">
          <div class="stat-icon memory">
            <el-icon size="32"><Connection /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ memoryUsage }}%</div>
            <div class="stat-label">内存使用</div>
            <div class="stat-trend">
              <span class="trend-warning">{{ usedMemory }}MB</span>
              / {{ totalMemory }}MB
            </div>
          </div>
          <div class="stat-progress">
            <div class="progress-bar memory" :style="{width: memoryUsage + '%'}"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 功能模块导航 -->
    <div class="modules-section">
      <h3 class="section-title">功能模块</h3>
      
      <div class="modules-grid">
        <div class="module-card" @click="navigateTo('/admin/shops')">
          <div class="module-header">
            <div class="module-icon shop">
              <el-icon size="24"><Shop /></el-icon>
            </div>
            <h4>店铺管理</h4>
          </div>
          <p>创建、编辑店铺信息，管理店铺状态</p>
          <div class="module-footer">
            <span class="module-count">{{ quickStats.totalShops }} 家店铺</span>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>

        <div class="module-card" @click="navigateTo('/admin/managers')">
          <div class="module-header">
            <div class="module-icon manager">
              <el-icon size="24"><UserFilled /></el-icon>
            </div>
            <h4>店长管理</h4>
          </div>
          <p>管理店长账户，权限分配和密码重置</p>
          <div class="module-footer">
            <span class="module-count">{{ quickStats.totalManagers }} 个账户</span>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>

        <div class="module-card" @click="navigateTo('/admin/monitoring')">
          <div class="module-header">
            <div class="module-icon system">
              <el-icon size="24"><Monitor /></el-icon>
            </div>
            <h4>系统监控</h4>
          </div>
          <p>实时监控系统状态，查看运行数据</p>
          <div class="module-footer">
            <span class="module-count">运行 {{ systemUptime }}</span>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>

        <div class="module-card" @click="runHealthCheck">
          <div class="module-header">
            <div class="module-icon health">
              <el-icon size="24"><Connection /></el-icon>
            </div>
            <h4>健康检查</h4>
          </div>
          <p>检查系统整体健康状况和性能指标</p>
          <div class="module-footer">
            <el-tag 
              :type="healthStatus === '健康' ? 'success' : 'danger'" 
              size="small"
              effect="light"
            >
              {{ healthStatus }}
            </el-tag>
            <el-icon class="arrow-icon"><ArrowRight /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近操作记录 -->
    <!-- <div class="recent-activity">
      <el-card title="最近活动" shadow="never">
        <template #header>
          <div class="card-header">
            <span>最近活动</span>
            <el-button type="text" icon="Refresh" @click="loadQuickStats">
              刷新
            </el-button>
          </div>
        </template>
        
        <div class="activity-list">
          <div class="activity-item" v-for="(activity, index) in recentActivities" :key="index">
            <div class="activity-icon" :class="activity.type">
              <el-icon>
                <component :is="activity.icon" />
              </el-icon>
            </div>
            <div class="activity-content">
              <div class="activity-title">{{ activity.title }}</div>
              <div class="activity-time">{{ activity.time }}</div>
            </div>
          </div>
          
          <div v-if="recentActivities.length === 0" class="no-activity">
            暂无最近活动记录
          </div>
        </div>
      </el-card>
    </div> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Shop, User, UserFilled, Monitor, Connection, ArrowRight } from '@element-plus/icons-vue'
import { useAuthStore } from '@renderer/store/modules/auth'
import { adminSystemApi } from '@renderer/api/admin'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const quickStats = ref({
  totalShops: 0,
  activeShops: 0,
  totalManagers: 0,
  activeManagers: 0,
  systemUptime: '0天',
  memoryUsage: 0,
  usedMemory: 0,
  totalMemory: 0,
  databaseStatus: 'connected'
})

const healthStatus = ref('未知')
const recentActivities = ref<Array<{
  type: string
  icon: string
  title: string
  time: string
}>>([
  {
    type: 'info',
    icon: 'Monitor',
    title: '系统启动完成',
    time: '刚刚'
  },
  {
    type: 'success',
    icon: 'User',
    title: '超级管理员登录成功',
    time: '2分钟前'
  }
])

// 计算属性
const userDisplayInfo = computed(() => authStore.getUserDisplayInfo)

const systemUptime = computed(() => {
  return quickStats.value.systemUptime || '0天'
})

const systemStatus = computed(() => {
  return quickStats.value.databaseStatus === 'connected' ? '正常运行' : '异常状态'
})

const memoryUsage = computed(() => {
  return Math.round(quickStats.value.memoryUsage) || 0
})

const usedMemory = computed(() => {
  return quickStats.value.usedMemory || 0
})

const totalMemory = computed(() => {
  return quickStats.value.totalMemory || 0
})

// 加载快速统计数据
const loadQuickStats = async () => {
  try {
    loading.value = true
    const response = await adminSystemApi.getSystemStats()
    const data = response.data.data
    
    quickStats.value = {
      totalShops: data.shopStats.totalCount,
      activeShops: data.shopStats.activeCount,
      totalManagers: data.userStats.managerCount,
      activeManagers: data.userStats.activeUsers,
      systemUptime: formatUptime(data.systemStatus.uptime),
      memoryUsage: data.systemStatus.jvmInfo.memoryUsage,
      usedMemory: data.systemStatus.jvmInfo.usedMemory,
      totalMemory: data.systemStatus.jvmInfo.totalMemory,
      databaseStatus: data.systemStatus.databaseStatus
    }
    
  } catch (error) {
    console.error('加载快速统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

// 运行健康检查
const runHealthCheck = async () => {
  try {
    const response = await adminSystemApi.getHealthCheck()
    const health = response.data.data
    
    healthStatus.value = health.overallHealth ? '健康' : '异常'
    
    if (health.overallHealth) {
      ElMessage.success('系统健康状态良好')
    } else {
      ElMessage.warning('系统健康状态存在问题')
    }
    
    // 导航到监控页面查看详情
    router.push('/admin/monitoring')
    
  } catch (error) {
    console.error('健康检查失败:', error)
    ElMessage.error('健康检查失败')
    healthStatus.value = '异常'
  }
}

// 导航到指定路由
const navigateTo = (path: string) => {
  router.push(path)
}

// 格式化运行时间
const formatUptime = (uptime: number) => {
  if (!uptime) return '0天'
  
  const days = Math.floor(uptime / (24 * 60 * 60 * 1000))
  const hours = Math.floor((uptime % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))
  
  if (days > 0) {
    return `${days}天${hours}小时`
  } else if (hours > 0) {
    return `${hours}小时`
  } else {
    const minutes = Math.floor((uptime % (60 * 60 * 1000)) / (60 * 1000))
    return `${minutes}分钟`
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await authStore.logout()
    router.push('/login')
  } catch (error) {
    console.error('登出失败:', error)
  }
}

// 背景粒子动画样式
const getParticleStyle = (index: number) => {
  const colors = ['#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD']
  const sizes = [60, 80, 100, 120, 140]
  const delays = [0, 2, 4, 6, 8]
  
  return {
    background: `radial-gradient(circle, ${colors[index - 1]}20, transparent)`,
    width: `${sizes[index - 1]}px`,
    height: `${sizes[index - 1]}px`,
    animationDelay: `${delays[index - 1]}s`
  }
}

// 页面加载
onMounted(() => {
  loadQuickStats()
})
</script>

<style scoped lang="scss">
.admin-dashboard {
  position: relative;
  min-height: 100vh;
  overflow-x: hidden;
  background: 
    radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.3) 0%, transparent 50%),
    linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

// 动态背景粒子
.background-particles {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
  
  .particle {
    position: absolute;
    border-radius: 50%;
    opacity: 0.6;
    animation: float 8s ease-in-out infinite;
    
    &:nth-child(1) { top: 10%; left: 10%; }
    &:nth-child(2) { top: 20%; right: 10%; }
    &:nth-child(3) { bottom: 30%; left: 20%; }
    &:nth-child(4) { bottom: 20%; right: 20%; }
    &:nth-child(5) { top: 50%; left: 50%; transform: translate(-50%, -50%); }
  }
}

@keyframes float {
  0%, 100% { transform: translateY(0px) scale(1); opacity: 0.6; }
  50% { transform: translateY(-20px) scale(1.1); opacity: 0.8; }
}

// 顶部导航栏
.top-navbar {
  position: relative;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 32px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  
  .navbar-left {
    .logo {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .logo-text {
        font-size: 24px;
        font-weight: 700;
        color: rgba(255, 255, 255, 0.95);
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }
  }
  
  .navbar-center {
    .page-title {
      font-size: 20px;
      font-weight: 600;
      color: rgba(255, 255, 255, 0.9);
      margin: 0;
      text-align: center;
    }
  }
  
  .navbar-right {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .user-details {
        .user-name {
          font-size: 14px;
          font-weight: 600;
          color: rgba(255, 255, 255, 0.95);
        }
        
        .user-role {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.7);
        }
      }
    }
    
    .logout-btn {
      background: rgba(245, 108, 108, 0.2);
      border: 1px solid rgba(245, 108, 108, 0.3);
      color: rgba(255, 255, 255, 0.95);
      
      &:hover {
        background: rgba(245, 108, 108, 0.3);
        transform: translateY(-2px);
      }
    }
  }
}

// 欢迎横幅
.welcome-banner {
  position: relative;
  z-index: 10;
  margin: 32px 32px;
  padding: 32px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(25px);
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  
  .banner-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    @media (max-width: 768px) {
      flex-direction: column;
      gap: 24px;
      text-align: center;
    }
    
    .welcome-text {
      h2 {
        font-size: 28px;
        font-weight: 700;
        color: rgba(255, 255, 255, 0.95);
        margin: 0 0 8px 0;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
      
      p {
        font-size: 16px;
        color: rgba(255, 255, 255, 0.8);
        margin: 0;
      }
    }
    
    .banner-actions {
      display: flex;
      gap: 16px;
      
      .el-button {
        padding: 12px 24px;
        font-size: 16px;
        border-radius: 12px;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
        }
      }
    }
  }
}

// 统计卡片区域
.stats-section {
  position: relative;
  z-index: 10;
  margin: 32px;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24px;
    
    @media (max-width: 1200px) {
      grid-template-columns: repeat(2, 1fr);
    }
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
    
    .stat-card {
      position: relative;
      padding: 24px;
      background: rgba(255, 255, 255, 0.25);
      backdrop-filter: blur(25px);
      border-radius: 20px;
      border: 1px solid rgba(255, 255, 255, 0.4);
      cursor: pointer;
      transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      overflow: hidden;
      
      &:hover {
        transform: translateY(-12px) scale(1.02);
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
      }
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 16px;
        color: rgba(255, 255, 255, 0.95);
        
        &.shop { background: linear-gradient(135deg, #4ECDC4, #44A08D); }
        &.manager { background: linear-gradient(135deg, #667eea, #764ba2); }
        &.system { background: linear-gradient(135deg, #f093fb, #f5576c); }
        &.memory { background: linear-gradient(135deg, #4facfe, #00f2fe); }
      }
      
      .stat-content {
        .stat-number {
          font-size: 36px;
          font-weight: 800;
          color: rgba(255, 255, 255, 0.95);
          line-height: 1;
          margin-bottom: 8px;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .stat-label {
          font-size: 14px;
          font-weight: 600;
          color: rgba(255, 255, 255, 0.8);
          margin-bottom: 12px;
        }
        
        .stat-trend {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.7);
          
          .trend-up { color: #4ECDC4; }
          .trend-warning { color: #F39C12; }
          .trend-stable { color: #27AE60; }
        }
      }
      
      .stat-progress {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 4px;
        background: rgba(255, 255, 255, 0.1);
        
        .progress-bar {
          height: 100%;
          background: linear-gradient(90deg, #4ECDC4, #44A08D);
          transition: width 1s ease;
          
          &.manager { background: linear-gradient(90deg, #667eea, #764ba2); }
          &.system { background: linear-gradient(90deg, #f093fb, #f5576c); }
          &.memory { background: linear-gradient(90deg, #4facfe, #00f2fe); }
        }
      }
    }
  }
}

// 功能模块区域
.modules-section {
  position: relative;
  z-index: 10;
  margin: 32px;
  
  .section-title {
    font-size: 24px;
    font-weight: 700;
    color: rgba(255, 255, 255, 0.95);
    margin: 0 0 24px 0;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .modules-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
    
    .module-card {
      padding: 28px;
      background: rgba(255, 255, 255, 0.12);
      backdrop-filter: blur(25px);
      border-radius: 20px;
      border: 1px solid rgba(255, 255, 255, 0.3);
      cursor: pointer;
      transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      
      &:hover {
        transform: translateY(-8px);
        box-shadow: 0 16px 50px rgba(0, 0, 0, 0.2);
        
        .arrow-icon {
          transform: translateX(8px);
        }
      }
      
      .module-header {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 16px;
        
        .module-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: rgba(255, 255, 255, 0.95);
          
          &.shop { background: linear-gradient(135deg, #4ECDC4, #44A08D); }
          &.manager { background: linear-gradient(135deg, #667eea, #764ba2); }
          &.system { background: linear-gradient(135deg, #f093fb, #f5576c); }
          &.health { background: linear-gradient(135deg, #4facfe, #00f2fe); }
        }
        
        h4 {
          font-size: 18px;
          font-weight: 700;
          color: rgba(255, 255, 255, 0.95);
          margin: 0;
        }
      }
      
      p {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.7);
        line-height: 1.6;
        margin: 0 0 20px 0;
      }
      
      .module-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .module-count {
          font-size: 12px;
          font-weight: 600;
          color: rgba(255, 255, 255, 0.8);
          padding: 6px 12px;
          background: rgba(255, 255, 255, 0.1);
          border-radius: 20px;
        }
        
        .arrow-icon {
          color: rgba(255, 255, 255, 0.6);
          transition: transform 0.3s ease;
        }
      }
    }
  }
}

// 最近活动区域
.recent-activity {
  position: relative;
  z-index: 10;
  margin: 32px;
  
  .el-card {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(25px);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-size: 18px;
        font-weight: 700;
        color: rgba(255, 255, 255, 0.95);
      }
    }
  }
  
  .activity-list {
    .activity-item {
      display: flex;
      align-items: center;
      padding: 16px 0;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      
      &:last-child {
        border-bottom: none;
      }
      
      .activity-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        &.success { background: rgba(103, 194, 58, 0.2); color: #4ECDC4; }
        &.info { background: rgba(64, 158, 255, 0.2); color: #667eea; }
        &.warning { background: rgba(230, 162, 60, 0.2); color: #F39C12; }
      }
      
      .activity-content {
        flex: 1;
        
        .activity-title {
          font-size: 14px;
          font-weight: 600;
          color: rgba(255, 255, 255, 0.95);
          margin-bottom: 4px;
        }
        
        .activity-time {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.6);
        }
      }
    }
    
    .no-activity {
      text-align: center;
      padding: 40px 0;
      color: rgba(255, 255, 255, 0.6);
      font-size: 14px;
    }
  }
}
</style>